package com.he.controller;

import com.he.annotation.AccessLimit;
import com.he.domain.Result;
import com.he.domain.dto.UserInfoDTO;
import com.he.domain.dto.UserPasswordDTO;
import com.he.domain.vo.UserInfoVO;
import com.he.service.LoginService;
import com.he.service.UserService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/11 9:36
 * @Desc 用户信息控制器
 */
@Tag(name = "用户信息")
@RestController
public class UserInfoController {
    @Resource
    private UserService userService;

    @Resource
    private LoginService loginService;

    @Operation(description = "获取登录用户信息")
    @GetMapping("/user/getUserInfo")
    public Result<UserInfoVO> getUserInfo() {
        return Result.success(userService.getUserInfo());
    }

    @Operation(description = "更新用户信息")
    @PutMapping("/user/updateUserInfo")
    @PreAuthorize("@ps.hasPermission('user:info:update')")
    public Result<?> updateUserInfo(@Validated @RequestBody UserInfoDTO userInfoDTO){
        userService.updateUserInfo(userInfoDTO);
        return Result.success();
    }

    @Operation(description = "修改用户密码")
    @PutMapping("/user/updatePassword")
    @PreAuthorize("@ps.hasPermission('user:password:update')")
    public Result<?> updatePassword(@Validated @RequestBody UserPasswordDTO userPasswordDTO){
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    @AccessLimit(seconds = 60, maxCount = 10)
    @Operation(description = "获取验证码")
    @PreAuthorize("@ps.hasPermission('user:password:update')")
    @GetMapping("/user/code")
    public Result<?> getCode(String username){
        loginService.sendCode(username);
        return Result.success();
    }

    @Operation(description = "修改用户头像")
    @PreAuthorize("@ps.hasPermission('user:avatar:update')")
    @PostMapping("/user/updateAvatar")
    public Result<?> updateAvatar(@RequestPart @RequestParam(value = "file") MultipartFile file){
        return Result.success(userService.updateAvatar(file));
    }

    @Operation(description = "删除用户")
    @PreAuthorize("@ps.hasPermission('user:avatar:update')")
    @DeleteMapping("/user/delete")
    public Result<?> deleteUser(@RequestParam Integer id){
        userService.deleteUser(id);
        return Result.success();
    }

}
